package com.bobi.tfca.ui.mainnavigation.user.register

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import androidx.navigation.findNavController
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.constants.CodeCategoryEnum
import com.bobi.tfca.constants.ReplyConstant
import com.bobi.tfca.databinding.FragmentRegisterMemberBinding
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.ResourceAPI
import com.bobi.tfca.network.response.MemberProfileResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.util.RealPathUtil
import com.bumptech.glide.Glide
import com.gingold.basislibrary.utils.BasisTimesUtils
import com.gingold.basislibrary.utils.BasisTimesUtils.OnDatePickerListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class RegisterMemberFragment : BaseFragment<FragmentRegisterMemberBinding, ViewModel>(
    FragmentRegisterMemberBinding::inflate,
    null,
    true
) {

    var headPhoto = ""
    var birthday = ""
    private lateinit var imagePickerLauncher: ActivityResultLauncher<Intent>
    private lateinit var imageView: ImageView

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private val REQUIRED_PERMISSIONS = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE
    )

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            if (permissions.all { it.value }) {
                // 如果所请求的所有权限都被授予，则执行相应的操作，比如打开相册
            } else {
                // 如果有任何一个权限被拒绝，则可以向用户解释为什么需要这些权限，并提供一个再次请求的机会
                Toast.makeText(requireActivity(), "选择图片需要权限", Toast.LENGTH_SHORT).show()
            }
        }


    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun checkPermissions(): Boolean {
        val isAllGranted = REQUIRED_PERMISSIONS.all {
            ContextCompat.checkSelfPermission(
                requireContext(),
                it
            ) == PackageManager.PERMISSION_GRANTED
        }
        // 如果权限没有授予，请求权限
        if (!isAllGranted) {
            requestPermissionLauncher.launch(REQUIRED_PERMISSIONS)
            return false
        } else {
            return true
        }
    }

    // 在适当的时候调用请求权限的方法
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun openPictureChooser() {
        if (checkPermissions()) {
            // 如果权限已被授予，则执行相应的操作，比如打开相册
            // 点击图片后，更改图片
            // 打开图片选择器
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            imagePickerLauncher.launch(intent)
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentRegisterMemberBinding,
        viewModel: ViewModel?,
        savedInstanceState: Bundle?
    ) {
        // 设置topPanel
        setTopPanelStyle(binding)
        // 设置上传图片监听
        imageView = binding.ivMemberHead
        imageView.setOnClickListener {
            uploadImage()
        }

        // 设置日期选择器监听
        setDateListener(binding.tvBirthday)

        binding.profile = MemberProfileResponse()

        // 注册图片选择器
        registerImagePickerResult()
    }

    private fun setDateListener(tvBirthday: TextView) {
        birthday = "1999-11-30"
        tvBirthday.setOnClickListener{
            showYearMonthDayPicker(tvBirthday)
        }
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentRegisterMemberBinding) {
        val topPanel = binding.topPanel
        topPanel.leftImage.setOnClickListener {
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        topPanel.rightButton.text = "下一步"
        topPanel.rightButton.setOnClickListener {
            var flag = true
            val gender = binding.etGender.text.toString()
            if (gender !in arrayOf("男", "女")) {
                Toast.makeText(requireActivity(), "性别不合法，请确认重新输入！", Toast.LENGTH_SHORT)
                    .show()
                flag = false
            }
            val memberProfile = binding.profile ?: MemberProfileResponse()
            val telephone = memberProfile.telephone
            if (telephone.length != 11) {
                Toast.makeText(requireActivity(), "电话号码输入不合法，请确认重新输入！", Toast.LENGTH_SHORT)
                    .show()
                flag = false
            }
            if (flag) {
                memberProfile.picture = headPhoto
                memberProfile.birthday = birthday
                LogUtil.i(memberProfile.toString())
                publicViewModel!!.memberProfile = memberProfile
                publicViewModel!!.codeCategory = CodeCategoryEnum.REGISTER_CODE
                // 设置回复
                publicViewModel!!.reply = ReplyConstant.REGISTER_REPLY
                // 下一步
                requireActivity().findNavController(R.id.app_nav)
                    .navigate(R.id.action_registerMemberFragment_to_emailCheckFragment)
            }
        }
        topPanel.titleText.visibility = View.GONE
    }

    /**
     * 年月日选择
     */
    private fun showYearMonthDayPicker(tvBirthday: TextView) {
        BasisTimesUtils.showDatePickerDialog(
            context,
            BasisTimesUtils.THEME_HOLO_DARK,
            "请选择年月日",
            2002,
            1,
            1,
            object : OnDatePickerListener {
                override fun onConfirm(year: Int, month: Int, dayOfMonth: Int) {
                    // 将月份和日期格式化为两位数字的形式
                    val formattedMonth = String.format("%02d", month)
                    val formattedDayOfMonth = String.format("%02d", dayOfMonth)
                    birthday = "$year-$formattedMonth-$formattedDayOfMonth"
                    tvBirthday.text = birthday
                }

                override fun onCancel() {
                }
            })
    }

    private fun registerImagePickerResult() {
        imagePickerLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val selectedImageUri: Uri? = result.data?.data
                    selectedImageUri?.let {
                        val file = getFileFromUri(selectedImageUri)
                        val requestFile = RequestBody.create(MediaType.parse("image/*"), file)
                        val body =
                            MultipartBody.Part.createFormData("file", file!!.name, requestFile)
                        if (body != null) {
                            LogUtil.i("选择了图片")
                            // 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
                            uploadImageToServer(
                                body
                            )
                        } else {
                            LogUtil.i("图片未选择")
                        }
                    }
                }
            }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun uploadImage() {
        openPictureChooser()
    }

    private fun getFileFromUri(uri: Uri): File? {
        val filePath = RealPathUtil.getRealPath(requireActivity(), uri)
        return if (filePath != null) File(filePath) else null
    }


    /**
     * 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
     */
    private fun uploadImageToServer(
        file: MultipartBody.Part
    ) {
        publicViewModel!!.apply {
            request(ResourceAPI::class.java).uploadImage(file).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")

                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                LogUtil.i("上传成功")
                                val url = it.data!!.data ?: ""
                                try {
                                    Glide.with(this@RegisterMemberFragment).load(url)
                                        .placeholder(R.drawable.defaultbg_h)
                                        .into(imageView)
                                    // 更改profile的头像
                                    headPhoto = url
                                } catch (e: Exception) {
                                    LogUtil.e( "加载图片时出现错误")
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}